using System;
using Microsoft.SPOT;

namespace Gadgeteer.Modules.Community.XBee
{
    /// <summary>
    /// Utility methods for converting bytes to hex strings
    /// </summary>
    public static class HexUtil
    {
        /// <summary>
        /// Convert a byte to hex string
        /// </summary>
        /// <param name="b">a byte</param>
        /// <returns>hex representation of the byte</returns>
        public static string ToHexString(byte b)
        {
            char[] array = new char[4];
            array[0] = '0';
            array[1] = 'x';
            array[2] = GetHexValue((int)(b / 16));
            array[3] = GetHexValue((int)(b % 16));
            return new string(array);
        }

        /// <summary>
        /// Convert a byte array to a comma delimited string
        /// </summary>
        /// <param name="bytes">bytes to turn into hex</param>
        /// <returns>comma delimited string</returns>
        public static string ToHexString(byte[] bytes)
        {
            // TODO: in 4.2,  use the new StringBuilder
            string result = String.Empty;
            for (int i = 0; i < bytes.Length; i++)
            {
                result += HexUtil.ToHexString((byte)bytes[i]) + ((i<bytes.Length - 1)? "," : "");
            }
            return result;
        }

        private static char GetHexValue(int i)
        {
            if (i < 10)
            {
                return (char)(i + 48);
            }
            return (char)(i - 10 + 65);
        }
    }
}
